<template>
  <div class="settings-container">
    <h2 class="page-title">系统设置</h2>
    
    <el-tabs v-model="activeTab" tab-position="left" class="settings-tabs">
      <!-- 基本设置 -->
      <el-tab-pane label="基本设置" name="basic">
        <h3 class="section-title">基本设置</h3>
        <el-form :model="basicSettings" :rules="basicRules" ref="basicForm" label-width="120px">
          <el-form-item label="系统名称" prop="systemName">
            <el-input v-model="basicSettings.systemName"></el-input>
          </el-form-item>
          <el-form-item label="系统Logo">
            <el-upload
              class="avatar-uploader"
              action="/api/upload"
              :show-file-list="false"
              :on-success="handleLogoSuccess"
              :before-upload="beforeLogoUpload">
              <img v-if="basicSettings.logo" :src="basicSettings.logo" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            <div class="upload-tip">建议尺寸: 200px × 200px，支持jpg、png格式</div>
          </el-form-item>
          <el-form-item label="系统描述" prop="description">
            <el-input v-model="basicSettings.description" type="textarea" :rows="4"></el-input>
          </el-form-item>
          <el-form-item label="联系电话" prop="contactPhone">
            <el-input v-model="basicSettings.contactPhone"></el-input>
          </el-form-item>
          <el-form-item label="联系邮箱" prop="contactEmail">
            <el-input v-model="basicSettings.contactEmail"></el-input>
          </el-form-item>
          <el-form-item label="版权信息" prop="copyright">
            <el-input v-model="basicSettings.copyright"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="saveBasicSettings">保存设置</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      
      <!-- 订单设置 -->
      <el-tab-pane label="订单设置" name="order">
        <h3 class="section-title">订单设置</h3>
        <el-form :model="orderSettings" :rules="orderRules" ref="orderForm" label-width="200px">
          <el-form-item label="自动取消未支付订单时间" prop="autoCancelTime">
            <el-input-number v-model="orderSettings.autoCancelTime" :min="5" :max="60"></el-input-number>
            <span class="unit-text">分钟</span>
            <div class="setting-desc">超过设定时间未支付的订单将自动取消</div>
          </el-form-item>
          <el-form-item label="自动完成已配送订单时间" prop="autoCompleteTime">
            <el-input-number v-model="orderSettings.autoCompleteTime" :min="10" :max="120"></el-input-number>
            <span class="unit-text">分钟</span>
            <div class="setting-desc">订单配送后超过设定时间将自动完成</div>
          </el-form-item>
          <el-form-item label="订单评价时间限制" prop="commentTimeLimit">
            <el-input-number v-model="orderSettings.commentTimeLimit" :min="1" :max="15"></el-input-number>
            <span class="unit-text">天</span>
            <div class="setting-desc">订单完成后超过设定时间将无法评价</div>
          </el-form-item>
          <el-form-item label="默认配送费" prop="defaultDeliveryFee">
            <el-input-number v-model="orderSettings.defaultDeliveryFee" :min="0" :max="20" :precision="2" :step="0.5"></el-input-number>
            <span class="unit-text">元</span>
          </el-form-item>
          <el-form-item label="免配送费最低消费" prop="freeDeliveryAmount">
            <el-input-number v-model="orderSettings.freeDeliveryAmount" :min="0" :max="100" :precision="2" :step="5"></el-input-number>
            <span class="unit-text">元</span>
            <div class="setting-desc">订单金额达到设定值时免配送费</div>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="saveOrderSettings">保存设置</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      
      <!-- 支付设置 -->
      <el-tab-pane label="支付设置" name="payment">
        <h3 class="section-title">支付设置</h3>
        <el-form :model="paymentSettings" :rules="paymentRules" ref="paymentForm" label-width="120px">
          <el-form-item label="启用微信支付">
            <el-switch v-model="paymentSettings.enableWechatPay"></el-switch>
          </el-form-item>
          <template v-if="paymentSettings.enableWechatPay">
            <el-form-item label="商户ID" prop="wechatMerchantId">
              <el-input v-model="paymentSettings.wechatMerchantId"></el-input>
            </el-form-item>
            <el-form-item label="API密钥" prop="wechatApiKey">
              <el-input v-model="paymentSettings.wechatApiKey" show-password></el-input>
            </el-form-item>
          </template>
          
          <el-form-item label="启用支付宝">
            <el-switch v-model="paymentSettings.enableAlipay"></el-switch>
          </el-form-item>
          <template v-if="paymentSettings.enableAlipay">
            <el-form-item label="商户ID" prop="alipayMerchantId">
              <el-input v-model="paymentSettings.alipayMerchantId"></el-input>
            </el-form-item>
            <el-form-item label="API密钥" prop="alipayApiKey">
              <el-input v-model="paymentSettings.alipayApiKey" show-password></el-input>
            </el-form-item>
          </template>
          
          <el-form-item label="启用校园卡支付">
            <el-switch v-model="paymentSettings.enableCampusCardPay"></el-switch>
          </el-form-item>
          <template v-if="paymentSettings.enableCampusCardPay">
            <el-form-item label="API地址" prop="campusCardApiUrl">
              <el-input v-model="paymentSettings.campusCardApiUrl"></el-input>
            </el-form-item>
            <el-form-item label="API密钥" prop="campusCardApiKey">
              <el-input v-model="paymentSettings.campusCardApiKey" show-password></el-input>
            </el-form-item>
          </template>
          
          <el-form-item>
            <el-button type="primary" @click="savePaymentSettings">保存设置</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      
      <!-- 通知设置 -->
      <el-tab-pane label="通知设置" name="notification">
        <h3 class="section-title">通知设置</h3>
        <el-form :model="notificationSettings" ref="notificationForm" label-width="200px">
          <h4 class="subsection-title">用户通知</h4>
          <el-form-item label="订单状态变更通知">
            <el-switch v-model="notificationSettings.user.orderStatusChange"></el-switch>
          </el-form-item>
          <el-form-item label="订单即将超时通知">
            <el-switch v-model="notificationSettings.user.orderTimeout"></el-switch>
          </el-form-item>
          <el-form-item label="优惠活动通知">
            <el-switch v-model="notificationSettings.user.promotion"></el-switch>
          </el-form-item>
          
          <h4 class="subsection-title">商家通知</h4>
          <el-form-item label="新订单通知">
            <el-switch v-model="notificationSettings.merchant.newOrder"></el-switch>
          </el-form-item>
          <el-form-item label="订单取消通知">
            <el-switch v-model="notificationSettings.merchant.orderCancel"></el-switch>
          </el-form-item>
          <el-form-item label="用户评价通知">
            <el-switch v-model="notificationSettings.merchant.userComment"></el-switch>
          </el-form-item>
          
          <h4 class="subsection-title">管理员通知</h4>
          <el-form-item label="新商家入驻申请通知">
            <el-switch v-model="notificationSettings.admin.newMerchant"></el-switch>
          </el-form-item>
          <el-form-item label="用户投诉通知">
            <el-switch v-model="notificationSettings.admin.userComplaint"></el-switch>
          </el-form-item>
          <el-form-item label="系统异常通知">
            <el-switch v-model="notificationSettings.admin.systemError"></el-switch>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="saveNotificationSettings">保存设置</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      
      <!-- 安全设置 -->
      <el-tab-pane label="安全设置" name="security">
        <h3 class="section-title">安全设置</h3>
        <el-form :model="securitySettings" :rules="securityRules" ref="securityForm" label-width="200px">
          <el-form-item label="密码最小长度" prop="passwordMinLength">
            <el-input-number v-model="securitySettings.passwordMinLength" :min="6" :max="20"></el-input-number>
            <span class="unit-text">位</span>
          </el-form-item>
          <el-form-item label="密码复杂度要求">
            <el-checkbox-group v-model="securitySettings.passwordComplexity">
              <el-checkbox label="number">必须包含数字</el-checkbox>
              <el-checkbox label="lowercase">必须包含小写字母</el-checkbox>
              <el-checkbox label="uppercase">必须包含大写字母</el-checkbox>
              <el-checkbox label="special">必须包含特殊字符</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="登录失败锁定次数" prop="loginFailLockCount">
            <el-input-number v-model="securitySettings.loginFailLockCount" :min="3" :max="10"></el-input-number>
            <span class="unit-text">次</span>
            <div class="setting-desc">连续登录失败达到设定次数将锁定账号</div>
          </el-form-item>
          <el-form-item label="账号锁定时长" prop="accountLockTime">
            <el-input-number v-model="securitySettings.accountLockTime" :min="5" :max="1440"></el-input-number>
            <span class="unit-text">分钟</span>
          </el-form-item>
          <el-form-item label="会话超时时间" prop="sessionTimeout">
            <el-input-number v-model="securitySettings.sessionTimeout" :min="10" :max="1440"></el-input-number>
            <span class="unit-text">分钟</span>
            <div class="setting-desc">用户无操作超过设定时间将自动退出登录</div>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="saveSecuritySettings">保存设置</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'Settings',
  data() {
    return {
      // 当前激活的标签页
      activeTab: 'basic',
      
      // 基本设置
      basicSettings: {
        systemName: '校园外卖平台',
        logo: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
        description: '为校园师生提供便捷的外卖订餐服务',
        contactPhone: '400-123-4567',
        contactEmail: 'support@campus-food.com',
        copyright: '© 2025 校园外卖平台 版权所有'
      },
      
      // 订单设置
      orderSettings: {
        autoCancelTime: 30,
        autoCompleteTime: 60,
        commentTimeLimit: 7,
        defaultDeliveryFee: 5.00,
        freeDeliveryAmount: 30.00
      },
      
      // 支付设置
      paymentSettings: {
        enableWechatPay: true,
        wechatMerchantId: 'wx123456789',
        wechatApiKey: 'abcdef123456',
        enableAlipay: true,
        alipayMerchantId: '2088123456789',
        alipayApiKey: '123456abcdef',
        enableCampusCardPay: true,
        campusCardApiUrl: 'https://api.campus.edu/payment',
        campusCardApiKey: '987654321'
      },
      
      // 通知设置
      notificationSettings: {
        user: {
          orderStatusChange: true,
          orderTimeout: true,
          promotion: true
        },
        merchant: {
          newOrder: true,
          orderCancel: true,
          userComment: true
        },
        admin: {
          newMerchant: true,
          userComplaint: true,
          systemError: true
        }
      },
      
      // 安全设置
      securitySettings: {
        passwordMinLength: 8,
        passwordComplexity: ['number', 'lowercase'],
        loginFailLockCount: 5,
        accountLockTime: 30,
        sessionTimeout: 120
      },
      
      // 表单验证规则
      basicRules: {
        systemName: [
          { required: true, message: '请输入系统名称', trigger: 'blur' }
        ],
        contactPhone: [
          { pattern: /^1[3-9]\d{9}$|^(\(\d{3,4}\)|\d{3,4}-|\s)?\d{7,14}$/, message: '请输入正确的联系电话', trigger: 'blur' }
        ],
        contactEmail: [
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ]
      },
      orderRules: {
        autoCancelTime: [
          { required: true, message: '请设置自动取消时间', trigger: 'blur' }
        ],
        autoCompleteTime: [
          { required: true, message: '请设置自动完成时间', trigger: 'blur' }
        ],
        commentTimeLimit: [
          { required: true, message: '请设置评价时间限制', trigger: 'blur' }
        ]
      },
      paymentRules: {
        wechatMerchantId: [
          { required: true, message: '请输入微信支付商户ID', trigger: 'blur' }
        ],
        wechatApiKey: [
          { required: true, message: '请输入微信支付API密钥', trigger: 'blur' }
        ],
        alipayMerchantId: [
          { required: true, message: '请输入支付宝商户ID', trigger: 'blur' }
        ],
        alipayApiKey: [
          { required: true, message: '请输入支付宝API密钥', trigger: 'blur' }
        ],
        campusCardApiUrl: [
          { required: true, message: '请输入校园卡支付API地址', trigger: 'blur' }
        ],
        campusCardApiKey: [
          { required: true, message: '请输入校园卡支付API密钥', trigger: 'blur' }
        ]
      },
      securityRules: {
        passwordMinLength: [
          { required: true, message: '请设置密码最小长度', trigger: 'blur' }
        ],
        loginFailLockCount: [
          { required: true, message: '请设置登录失败锁定次数', trigger: 'blur' }
        ],
        accountLockTime: [
          { required: true, message: '请设置账号锁定时长', trigger: 'blur' }
        ],
        sessionTimeout: [
          { required: true, message: '请设置会话超时时间', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    // 获取系统设置
    this.fetchSettings()
  },
  methods: {
    // 获取系统设置
    fetchSettings() {
      // 根据API文档 8.1 获取系统配置
      axios.get('/api/settings')
        .then(response => {
          if (response.data.code === 200) {
            const data = response.data.data
            
            // 更新基本设置
            if (data.basic) {
              this.basicSettings = {
                ...this.basicSettings,
                ...data.basic
              }
            }
            
            // 更新订单设置
            if (data.order) {
              this.orderSettings = {
                ...this.orderSettings,
                ...data.order
              }
            }
            
            // 更新支付设置
            if (data.payment) {
              this.paymentSettings = {
                ...this.paymentSettings,
                ...data.payment
              }
            }
            
            // 更新通知设置
            if (data.notification) {
              this.notificationSettings = {
                ...this.notificationSettings,
                ...data.notification
              }
            }
            
            // 更新安全设置
            if (data.security) {
              this.securitySettings = {
                ...this.securitySettings,
                ...data.security
              }
            }
          } else {
            this.$message.error(response.data.message || '获取系统设置失败')
          }
        })
        .catch(error => {
          console.error('获取系统设置失败', error)
          this.$message.error('获取系统设置失败')
        })
    },
    
    // 保存基本设置
    saveBasicSettings() {
      this.$refs.basicForm.validate(valid => {
        if (valid) {
          // 根据API文档 8.2 更新系统配置
          axios.put('/api/settings/basic', this.basicSettings)
            .then(response => {
              if (response.data.code === 200) {
                this.$message.success('基本设置保存成功')
              } else {
                this.$message.error(response.data.message || '保存基本设置失败')
              }
            })
            .catch(error => {
              console.error('保存基本设置失败', error)
              this.$message.error('保存基本设置失败')
            })
        } else {
          return false
        }
      })
    },
    
    // 保存订单设置
    saveOrderSettings() {
      this.$refs.orderForm.validate(valid => {
        if (valid) {
          // 根据API文档 8.2 更新系统配置
          axios.put('/api/settings/order', this.orderSettings)
            .then(response => {
              if (response.data.code === 200) {
                this.$message.success('订单设置保存成功')
              } else {
                this.$message.error(response.data.message || '保存订单设置失败')
              }
            })
            .catch(error => {
              console.error('保存订单设置失败', error)
              this.$message.error('保存订单设置失败')
            })
        } else {
          return false
        }
      })
    },
    
    // 保存支付设置
    savePaymentSettings() {
      // 根据启用状态动态验证
      let validateFields = []
      
      if (this.paymentSettings.enableWechatPay) {
        validateFields.push('wechatMerchantId', 'wechatApiKey')
      }
      
      if (this.paymentSettings.enableAlipay) {
        validateFields.push('alipayMerchantId', 'alipayApiKey')
      }
      
      if (this.paymentSettings.enableCampusCardPay) {
        validateFields.push('campusCardApiUrl', 'campusCardApiKey')
      }
      
      if (validateFields.length > 0) {
        this.$refs.paymentForm.validateField(validateFields, valid => {
          if (!valid) {
            // 保存支付设置
            this.updatePaymentSettings()
          }
        })
      } else {
        this.updatePaymentSettings()
      }
    },
    
    // 更新支付设置
    updatePaymentSettings() {
      // 根据API文档 8.2 更新系统配置
      axios.put('/api/settings/payment', this.paymentSettings)
        .then(response => {
          if (response.data.code === 200) {
            this.$message.success('支付设置保存成功')
          } else {
            this.$message.error(response.data.message || '保存支付设置失败')
          }
        })
        .catch(error => {
          console.error('保存支付设置失败', error)
          this.$message.error('保存支付设置失败')
        })
    },
    
    // 保存通知设置
    saveNotificationSettings() {
      // 根据API文档 8.2 更新系统配置
      axios.put('/api/settings/notification', this.notificationSettings)
        .then(response => {
          if (response.data.code === 200) {
            this.$message.success('通知设置保存成功')
          } else {
            this.$message.error(response.data.message || '保存通知设置失败')
          }
        })
        .catch(error => {
          console.error('保存通知设置失败', error)
          this.$message.error('保存通知设置失败')
        })
    },
    
    // 保存安全设置
    saveSecuritySettings() {
      this.$refs.securityForm.validate(valid => {
        if (valid) {
          // 根据API文档 8.2 更新系统配置
          axios.put('/api/settings/security', this.securitySettings)
            .then(response => {
              if (response.data.code === 200) {
                this.$message.success('安全设置保存成功')
              } else {
                this.$message.error(response.data.message || '保存安全设置失败')
              }
            })
            .catch(error => {
              console.error('保存安全设置失败', error)
              this.$message.error('保存安全设置失败')
            })
        } else {
          return false
        }
      })
    },
    
    // 处理Logo上传成功
    handleLogoSuccess(res, file) {
      if (res.code === 200) {
        this.basicSettings.logo = res.data.url
      } else {
        this.$message.error(res.message || 'Logo上传失败')
      }
    },
    
    // Logo上传前的验证
    beforeLogoUpload(file) {
      const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      
      if (!isJPGOrPNG) {
        this.$message.error('上传Logo只能是JPG或PNG格式!')
      }
      
      if (!isLt2M) {
        this.$message.error('上传Logo大小不能超过2MB!')
      }
      
      return isJPGOrPNG && isLt2M
    }
  }
}
</script>

<style scoped>
.settings-container {
  padding: 20px;
}

.page-title {
  margin-bottom: 20px;
  font-size: 24px;
  font-weight: bold;
}

.settings-tabs {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.section-title {
  margin-bottom: 20px;
  font-size: 18px;
  font-weight: bold;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.subsection-title {
  margin: 20px 0 10px;
  font-size: 16px;
  font-weight: bold;
  color: #606266;
}

.unit-text {
  margin-left: 10px;
  color: #606266;
}

.setting-desc {
  margin-top: 5px;
  font-size: 12px;
  color: #909399;
}

.avatar-uploader {
  width: 178px;
  height: 178px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.upload-tip {
  margin-top: 5px;
  font-size: 12px;
  color: #909399;
}
</style>